<template>
  <div>
    <!-- 好友列表 -->
    <div v-for="friend in friends" :key="friend.id" @click="selectFriend(friend)">
      {{ friend.name }} <span v-if="friend.online">(在线)</span>
    </div>

    <!-- 聊天区域 -->
    <div v-if="selectedFriend">
      <div v-for="msg in messages" :key="msg.id">
        [{{ msg.from }}]: {{ msg.content }}
      </div>
      <input v-model="inputMsg" @keyup.enter="sendMessage" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const ws = ref(null);
const inputMsg = ref('');
const messages = ref({'from':'小王'});
const friends = ref([{ id: 'user2', name: '小明', online: false }]);
const selectedFriend = ref({ id: 'user2', name: '小明', online: false });

// 初始化WebSocket连接
onMounted(() => {
  const userId = localStorage.getItem('userId')||'user2';
  ws.value = new WebSocket(`ws://localhost:8081/ws`);

  ws.value.onopen = () => {
    // 发送登录请求
    ws.value.send(JSON.stringify({
      type: 'LOGIN',
      userId: userId
    }));
    // 拉取离线消息
    ws.value.send(JSON.stringify({
      type: 'PULL_OFFLINE_MSG',
      userId: userId
    }));
    // 拉取历史记录
    ws.value.send(JSON.stringify({
      type: "PULL_HISTORICAL_CHAT_MSG",
      toUserId: userId,
      fromUserId: 1
    }));
  };

  // 接收消息
  ws.value.onmessage = (event) => {
    const msg = JSON.parse(event.data);
    if (msg.type === 'OFFLINE_MSG') {
      messages.value.push({
        from: msg.from,
        content: msg.content,
        isOffline: true
      });
    } else if (msg.type === 'SINGLE_MSG') {
      messages.value.push({
        from: msg.from,
        content: msg.content
      });
    }
  };
});

// 发送消息
const sendMessage = () => {
    if (ws.value.readyState === WebSocket.CLOSING || ws.value.readyState === WebSocket.CLOSED) {
        // 重新连接
        ws.value = new WebSocket('ws://localhost:8081/ws');
    }
  if (inputMsg.value.trim() && selectedFriend.value) {
    ws.value.send(JSON.stringify({
      type: 'SINGLE_MSG',
      from: localStorage.getItem('userId')||1,
      to: selectedFriend.value.id,
      content: inputMsg.value.trim()
    }));
    inputMsg.value = '';
  }
};
</script>